/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.j4sc.testharness;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class StubService {

    private final int port;

    private Server server;

    private int respondStatus = HttpStatus.SC_ACCEPTED;
    private Map<String, String> headers = new HashMap<String, String>();
    private int delayInMillis;
    private String body;

    private String lastRequestBody;

    public StubService(int port) {
        this.port = port;
    }

    public StubService withStatus(int statusCode) {
        this.respondStatus = statusCode;
        return this;
    }

    public StubService withBody(String body) {
        this.body = body;
        return this;
    }

    public StubService withHeader(String name, String value) {
        headers.put(name, value);
        return this;
    }

    public StubService after(int delayInMillis) {
        this.delayInMillis = delayInMillis;
        return this;
    }

    public void start() throws Exception {
        server = new Server(port);
        Context root = new Context(server, "/", Context.SESSIONS);
        root.addServlet(new ServletHolder(new HttpStubServlet()), "/*");
        server.start();
    }

    public void stop() throws Exception {
        if (server != null) {
            server.stop();
        }
    }

    public String getLastRequestBody() {
        return lastRequestBody;
    }

    private class HttpStubServlet extends HttpServlet {

        private static final long serialVersionUID = -7511611496236453658L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                IOException {
            StubService.this.lastRequestBody = IOUtils.toString(request.getReader());
            if (delayInMillis > 0) {
                try {
                    Thread.sleep(delayInMillis);
                } catch (InterruptedException ignore) {
                }
            }

            response.setStatus(respondStatus);
            for (Map.Entry<String, String> header : headers.entrySet()) {
                if (header.getValue() != null) {
                    response.addHeader(header.getKey(), header.getValue());
                }
            }

            if (body != null) {
                response.getWriter().write(body);
            }
            response.flushBuffer();
        }
    }
}
